#!/bin/sh
source /etc/profile
## java env
## export JAVA_HOME=/usr/java/jdk1.8.0_241-amd64
## export JRE_HOME=$JAVA_HOME/jre

## com.openlookeng.user.service name
APP_NAME=openlookeng-social-insurance
JAVA_OPTS="-Xms512m -Xmx1024m"
ACTIVE=test

AGENT_SERVICE_NAME="$APP_NAME"_"$ACTIVE"

SERVICE_DIR=/disk/openlookeng-social-insurance
SERVICE_NAME=$APP_NAME
JAR_NAME=$SERVICE_NAME\.jar
PID=$SERVICE_NAME\.pid

cd $SERVICE_DIR

#检查程序是否在运行
is_exist(){
  V_PID=`ps -ef|grep $JAR_NAME|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${V_PID}" ]; then
   return 1
  else
    return 0
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "=== ${SERVICE_NAME} is running PID is ${V_PID} ==="
  else
    echo "=== ${SERVICE_NAME} is not running ==="
  fi
}

case "$1" in

    start)
	    is_exist
		if [ $? -eq "0" ]; then
		    echo "=== $SERVICE_NAME is already running PID=$V_PID ==="
		else
            BUILD_ID=dontKillMe
            nohup java -jar $JAR_NAME  --spring.profiles.active=$ACTIVE  >/dev/null 2>&1 &
            echo $! > $SERVICE_DIR/$PID
            echo "=== start ${SERVICE_NAME} success PID=$! ==="
		fi
        ;;

    stop)
	    P_ID=$(cat $SERVICE_DIR/$PID)
		echo "=== $SERVICE_NAME PID=$P_ID begin kill $P_ID ==="
	    kill $P_ID
		rm -rf $SERVICE_DIR/$PID

		sleep 2

		is_exist
		if [ $? -eq "0" ]; then
		    echo "=== $SERVICE_NAME 2 PID=$V_PID begin kill 9 $V_PID"
			kill -9 $V_PID
			sleep 2
			echo "=== $SERVICE_NAME process stopped ==="
		else
		    echo "=== $SERVICE_NAME is not running ==="
		fi
        ;;

    restart)
        $0 stop
        sleep 2
        $0 start
        echo "=== restart $SERVICE_NAME success ==="
        ;;
    status)
	    status
	    ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        ;;

esac
exit 0

